/**
 * Created by zhangjinrui on 17/6/27.
 */

public class Solution542 {

    public static void main(String args[]) {
        Solution542 s = new Solution542();
    }

    public int[][] updateMatrix(int[][] matrix) {
        int n = matrix.length;
        if (n == 0) {
            return new int[0][0];
        }
        int m = matrix[0].length;
        if (m == 0) {
            return new int[n][m];
        }

        int[][] ret = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (matrix[i][j] == 0) {
                    ret[i][j] = 0;
                } else {
                    ret[i][j] = 20000;
                    if (i - 1 >= 0) {
                        ret[i][j] = Math.min(20000, ret[i - 1][j] + 1);
                    }
                    if (j - 1 >= 0) {
                        ret[i][j] = Math.min(ret[i][j], ret[i][j - 1] + 1);
                    }
                }
            }
        }

        for (int i = n - 1; i >= 0; i--) {
            for (int j = m - 1; j >= 0; j--) {
                if (i + 1 < n) {
                    ret[i][j] = Math.min(ret[i + 1][j] + 1, ret[i][j]);
                }
                if (j + 1 < m) {
                    ret[i][j] = Math.min(ret[i][j], ret[i][j + 1] + 1);
                }
            }
        }
        return ret;
    }

}
